package wang.lx.mybatis.shiro;

import java.text.ParseException;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.nimbusds.jose.JOSEException;

import wang.lx.mybatis.common.JwtToken;
import wang.lx.mybatis.common.SysDefaultRole;
import wang.lx.mybatis.entity.SysRole;
import wang.lx.mybatis.entity.SysUser;
import wang.lx.mybatis.service.SysUserServiceI;

public class JwtRealm   extends MyRealm {
    
    @Autowired
    SysUserServiceI sysUserServiceI;
    
    public boolean supports(AuthenticationToken token) {
        return token != null && JwtAuthenticationToken.class.isAssignableFrom(token.getClass());
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwtStr = (String)token.getPrincipal();
        JwtToken jwtToken = null;
        // 获取payload
        try
        {
            jwtToken = this.sysUserServiceI.getJwtToken(jwtStr);
        }
        catch (ParseException | JOSEException e)
        {
            e.printStackTrace();
            throw new AuthenticationException("token验证失败");
        }
        // 查下
        SysUser query = new SysUser();
        //// TODO 查找真的TOKEN
        query.setUserid(jwtToken.getToken());
        SysUser sysuser = this.sysUserServiceI.findUserByUser(query);
        boolean isok = true;
        if(sysuser == null){
            isok = false;
        }
        if(!isok)
            throw new AuthenticationException("未能获取用户");
        //TODO 获取角色与权限信息
        {
            SysRole role = new SysRole();
            role.setId(SysDefaultRole.ROLE_USER.getRoleId());
            role.setRolename(SysDefaultRole.ROLE_USER.getRoleName());
            sysuser.getRoles().add(role);
            role = new SysRole();
            role.setId(SysDefaultRole.ROLE_ADMIN.getRoleId());
            role.setRolename(SysDefaultRole.ROLE_ADMIN.getRoleName());
            sysuser.getRoles().add(role);
            // 设置当前角色
            sysuser.setCurrentRole(role);
        }

        AuthenticationInfo info = new SimpleAuthenticationInfo(sysuser, jwtStr, getName());
        return info;
    }
    
}
